package com.anycl.design.j2ee.interceptingfilter.instance;

import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.List;

@Slf4j
public class DefaultFilterChain implements FilterChain {

    private List<Filter> filters = new LinkedList<>();

    private TargetResource target;

    // 当前正在执行的过滤器索引
    private int currentFilterIndex = 0;

    @Override
    public void execute() {
        if (filters.isEmpty() || filters.size() == currentFilterIndex) {
            target.execute();
        } else {
            Filter filter = filters.get(currentFilterIndex);
            currentFilterIndex++;
            filter.doFilter(this);

        }
    }

    @Override
    public void setTarget(TargetResource target) {
        this.target = target;
    }

    @Override
    public void addFilter(Filter filter) {
        this.filters.add(filter);
    }
}
